// pages/productDetails/productDetails.js
const app = getApp()
var api = require('../../../utils/api.js')
var util = require('../../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    numbers: 1,
    modifyPriceCol: true,
    share:1,
    share_id:'',
    preferentialPrice:0,
    cartCount:0,
    authorize:true, //授权
    join_shop:0,
    join_price:0,
    lastTime:0,
    focus:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.hideShareMenu() // 隐藏分享按钮

    if (options.shop_id) {
      this.setData({
        shop_id: options.shop_id
      })
    }

    if (options.sku_code) {
      this.setData({
        sku_code: options.sku_code
      })
    }
    // this.getProductInfo();
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    // this.setData({
    //   user_flag: wx.getStorageSync('accountInfo').user_flag
    // })
    this.getProductInfo();
    this.userStatus();
    this.cartNum();
  },
   focusCol:function(){
      this.setData({
         focus: false
      })
   },
  

  //获取个人状态详情
  userStatus: function (e) {
    var that = this;
    api.POST({
      params: "",
      url: app.globalData.base_url + 'user/status',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          app.globalData.userStatus = res.data.data
          if (res.data.data.inn_id) {
            that.setData({
              inn_id: res.data.data.inn_id
            })
          }
          that.setData({
            avatar: res.data.data.avatar,
            nickname: res.data.data.nickname,
            user_flag: res.data.data.user_flag,
            audit_status: res.data.data.audit_status || null,
            unread: res.data.data.unread,
            account_type: res.data.data.account_type
          })
        }
      },
      fail: function (fail) {
        util.showError("网络错误，请检查网络");
      }
    })
  },

  getProductInfo: function() {
    var that = this;
    var params = new Object()
    params.sku_code = this.data.sku_code;
    if (this.data.shop_id) {
      params.shop_id = this.data.shop_id;
    }
    util.showLoading("数据加载中..");
    api.POST({
      params: params,
      url: app.globalData.base_url + 'goods/getInfo',
      success: function(res) {
        util.hiddenLoading();
        if (util.isEmpty(res.data.code)) {
          that.setData({
            rawData: res.data.data
            // newPrice: res.data.data.current_price
          });
        }

      },
      fail: function(fail) {
        util.showErrorPath("../../../", "获取失败，请检查网络");
      }
    })
  },

  //手动输入数量
   inputNumber:function(e){
      var num=e.detail.value;
      num = num.replace(/^0/g, '');
      var stock = this.data.rawData.stock/1;
      if (stock && num!='') {
         if (num >= stock) {
            util.showError("库存不足")
         }
         num <= stock ? num = num : num = stock
      }
      this.setData({
         numbers: num
      })
   },

   //检查输入数量是否为空
   checkInputNumber:function(){
      var num = this.data.numbers;
      var reg = /^\s*$/g;
      if (reg.test(num) || num == null || num == "") {
         this.setData({
            numbers: 1
         })
      }
   },

  addNum: function() {
    var num = this.data.numbers;
    var stock = this.data.rawData.stock;
    num++
    if (stock){
      if (num >= stock){
        util.showError("库存不足，不能再添加啦~")
      }
      num <= stock ? num = num : num=stock
    }
    this.setData({
      numbers: num
    })
  },
  minusNum: function() {
    var num = this.data.numbers;
    if (num > 1) {
      num--;
    }
    this.setData({
      numbers: num
    })
  },
  join_shop:function(){
    if (this.data.share==2){
      return false
    }
    var join_shop = this.data.join_shop;
    if (join_shop == 1) {
      this.setData({
        join_shop: 0
      })
    } else if (join_shop == 0) {
      this.setData({
        join_shop: 1
      })
    }
  },
  join_price: function () {
    if (this.data.share == 2) {
      return false
    }
    var join_price = this.data.join_price;
    if (join_price == 1) {
      this.setData({
        join_price: 0
      })
    } else if (join_price == 0) {
      this.setData({
        join_price: 1
      })
    }
  },

  // 加入购物车
  addCart: function() {
     var that = this; 
     setTimeout(function () {
        var params = new Object()
        params.sku_code = that.data.sku_code;
        params.num = that.data.numbers;
        if (that.data.shop_id) {
           params.shop_id = that.data.shop_id;
        }
        api.POST({
           params: params,
           url: app.globalData.base_url + 'shoppingcart/addGoods',
           success: function (res) {
              if (util.isEmpty(res.data.code)) {
                 util.showSuccess("加入成功");
                 that.cartNum();
              } else {
                 util.showStatus(res.data.message)
              }

           },
           fail: function (fail) {
              util.showErrorPath("../../../", "获取失败，请检查网络");
           }
        })
     }, 500)
  },

  //购物车商品数量
  cartNum:function(){
    var that = this;
    api.POST({
      params: '',
      url: app.globalData.base_url + 'shoppingcart/countGoods',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          // util.showSuccess("加入成功")
          // console.log(res)
          that.setData({
            cartCount: res.data.data.countNum
          })
        }

      },
      fail: function (fail) {
        util.showErrorPath("../../../", "获取失败，请检查网络");
      }
    })
  },
  // 立即购买
  pay: function(e) {
    var curTime = e.timeStamp;
    var lastTime = this.data.lastTime;
    this.setData({
      lastTime: curTime
    })
    if (lastTime > 0) {
      if (curTime - lastTime < 500) {
        return false;
      }
    }
   var that=this;
     setTimeout(function(){
        var orderList = [];
        var box = new Object();
        box.num = that.data.numbers;
        box.stock = that.data.rawData.stock;
        if (that.data.shop_id) {
           box.shop_id = that.data.shop_id;
           var shop_id = that.data.shop_id;
           if (box.num > box.stock) {
              util.showStatus("库存不足");
              return;
           }
        }
        if (that.data.uid) {
           var uid = that.data.uid;
        } else {
           var uid = ''
        }

        box.sku_code = that.data.sku_code;
        box.current_price = that.data.rawData.current_price;
        box.gname = that.data.rawData.gname;
        box.image = that.data.rawData.image;
        box.degree = that.data.rawData.degree;
        box.degree_unit = that.data.rawData.degree_unit;
        box.volume = that.data.rawData.volume;
        box.volume_unit = that.data.rawData.volume_unit;
        box.total = (that.data.numbers * that.data.rawData.current_price).toFixed(2);
        orderList.push(box);
        wx.setStorageSync('orderList', orderList);
        if (shop_id) {
           wx.navigateTo({
              url: '/index/pages/order/order?shop_id=' + shop_id
           })
        } else if (uid) {
           wx.navigateTo({
              url: '/index/pages/order/order?uid=' + uid
           })
        } else {
           wx.navigateTo({
              url: '/index/pages/order/order'
           })
        }
     },500)
  },

  linkCart: function() {
    wx.navigateTo({
      url: '/index/pages/cart/cart'
    })
  },
  onShareAppMessage: function(res) {

    var that = this;
    var uid = '&uid=' + wx.getStorageSync('accountInfo').uid;
    var inn_id = that.data.inn_id;
    var share_id = that.data.share_id;
    if (share_id){
      var share_id = '&share_id=' + share_id;
      var inn_id = '&inn_id=' + inn_id;
      var url = '/agent/pages/shareStoreProductDetail/shareStoreProductDetail?sku_code=' + that.data.sku_code + inn_id + share_id + uid      
    }else{
      var url = '/index/pages/productDetails/productDetails?sku_code=' + that.data.sku_code
    }
    console.log('productDetails onShareAppMessage start summer@17:47')
    console.log('uid');
    console.log(uid);
    console.log('inn_id');
    console.log(inn_id);
    console.log('share_id');
    console.log(share_id);
    console.log('url');
    console.log(url);
    console.log('productDetails onShareAppMessage end summer@17:47')
        
    if (res.from === 'button') {
      // 来自页面内转发按钮
      return {
        title: that.data.rawData.gname,
        path: url,
        imageUrl: that.data.rawData.share_img,
        success: function(res) {
          that.setData({
            share:"",
            share_id:"",
            modifyPriceCol:true
          })
        },
        fail: function(res) {
          // 转发失败
        }
      }
    }
  },
  modifyPrice: function() {
    this.setData({
      modifyPriceCol: false,
      share: 1,
      newPrice:'',
      preferentialPrice:0
    })
  },
  closeModifyPrice: function() {
    this.setData({
      modifyPriceCol: true,
      share: 1
    })
  },
  newPrice: function(e) {
    var reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
    var money = e.detail.value/1
    var newPrice = this.data.newPrice/1
    var current_price = this.data.rawData.current_price / 1
    var minprice = this.data.rawData.share_bottom_price/1
    var preferentialPrice = this.data.preferentialPrice
    if (reg.test(money) ) {
      if (money!=0){
        money = money.toFixed(2);
        preferentialPrice = (current_price - money).toFixed(2);
      }else{
        money=''
        preferentialPrice = 0;
      }
    } else {
      money = ""
    }
    this.setData({
      newPrice: money,
      preferentialPrice: preferentialPrice
    })
  },
  //确认修改价格
  submitModifyPrice: function (e) {
    var that = this;
   var curTime = e.timeStamp;
   var lastTime = this.data.lastTime;
   this.setData({
      lastTime: curTime,
      focus: false
   })
   if (lastTime > 0) {
      if (curTime - lastTime < 500) {
         return false;
      }
   }
   
    var params = new Object()
    
    var timer = setTimeout(function(){

      var newPrice = parseFloat(that.data.newPrice)
      var share_bottom_price = parseFloat(that.data.rawData.share_bottom_price)
      var current_price = parseFloat(that.data.rawData.current_price)

      if (isNaN(newPrice)) {
        newPrice = 0
      }

      if (newPrice==''){
        params.share_price = that.data.rawData.current_price;
      }else{
        if (newPrice < share_bottom_price) {
          util.showStatus("价格不得低于" + share_bottom_price);
          that.setData({
            newPrice: '',
            preferentialPrice: 0
          })
          return false
        }
        if (newPrice > current_price) {
          that.setData({
            newPrice: '',
            preferentialPrice: 0
          })
          util.showStatus("价格不得高于" + current_price);
          return false
        }
        params.share_price = that.data.newPrice;
      }
      

      if (that.data.join_price==1){
        params.is_sync = 1;
      }
      params.sku_code = that.data.rawData.sku_code;

      api.POST({
        params: params,
        url: app.globalData.base_url + 'goods/shareSub',
        success: function (res) {
          if (util.isEmpty(res.data.code)) {
            util.showStatus("修改成功，请点击分享");
            console.log(res.data);
            that.getProductInfo();
            that.setData({
              share: 2,
              share_id: res.data.data.share_id,
              share_img: res.data.data.code_img,
              inn_id: res.data.data.inn_id
            })
            clearTimeout(timer);
          } else {
            util.showStatus(res.data.message)
          }

        },
        fail: function (fail) {
          util.showErrorPath("../../../", "获取失败，请检查网络");
        }
      })
    },300)
  },
  priceInput:function(e){
    var reg = /((^[1-9]\d*)|^0)(\.\d{0,2}){0,1}$/;
    var money = e.detail.value;
    if (!reg.test(money)) {
      money = money.slice(0, money.length - 1)
    }
    this.setData({
      share: 1,
      newPrice: money
    })
  },

  getImageInfo: function () {
    var that = this;
    var img = this.data.share_img
    wx.getImageInfo({
      src: img,
      success: function (res) {
        that.setData({
          share_qr_code: res.path
        })
        setTimeout(function () {
          that.saveImage()
        }, 500);
      }
    })
  },
  handler: function (e) {
    if (e.detail.authSetting["scope.writePhotosAlbum"]) {
      this.saveImage();
      this.setData({
        authorize: true
      })
    }
  },
  saveImage: function () {
    var that = this;
    wx.saveImageToPhotosAlbum({
      filePath: that.data.share_qr_code,
      success(res) {
        util.showError('保存图片成功')
      },
      fail: function (fail) {
        if (fail.errMsg == "saveImageToPhotosAlbum:fail auth deny") {
          that.setData({
            authorize:false
          })
        }
      }
    })
  }


})